package cn.tedu.csmall.business.service.impl;

import cn.tedu.csmall.business.service.IBusinessService;
import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.order.service.IOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
@Slf4j //提供log对象
public class BusinessServiceImpl implements IBusinessService {

    @DubboReference
    private IOrderService dubboOrderService;

    @GlobalTransactional
    @Override
    public void buy() {
        //模拟购物的流程
        //创建一个OrderAddDTO类，为其赋值
        OrderAddDTO orderAddDTO = new OrderAddDTO();
        orderAddDTO.setCommodityCode("PU200");
        orderAddDTO.setUserId("UU100");
        orderAddDTO.setMoney(500);
        orderAddDTO.setCount(10);
        //TODO:调用order模块，进行购物
        dubboOrderService.orderAdd(orderAddDTO);
        //模拟过程。目前先输出到控制台观察结果
        log.info("新增订单的信息为：{}",orderAddDTO);
        //模拟事务分支出现异常，然后回滚操作
        if(Math.random()<0.5){
//            System.out.println(0/0);
            throw new
                    CoolSharkServiceException(
                            ResponseCode.INTERNAL_SERVER_ERROR,"发生随机异常，本次操作回滚");
        }
    }
}
